<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请入分类名称" clearable v-model="likeName">
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="isDelete" placeholder="请选择状态">
            <el-option label="正常" value="0"></el-option>
            <el-option label="已删除" value="1"></el-option>
            <el-option label="已禁用" value="2"></el-option>
          </el-select>
          <el-button type="primary" @click="searchType" round>查询</el-button>
          <el-button @click="resetInput" round>重置</el-button>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="addDialogVisible=true">添加分类</el-button>
        </el-col>
      </el-row>

      <el-table
          :data="typeList"
          border
          style="width: 100%">
        <el-table-column prop="typeId" label="ID" align="center"></el-table-column>
        <el-table-column prop="typeName" label="分类名称(用途)" align="center"></el-table-column>
        <el-table-column prop="flowerCount" label="相关商品(个)" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isDelete" label="状态" :formatter="statusFormatter" align="center"></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="danger" @click="removeType(scope.row)">删除</el-button>
            <el-button type="warning" @click="disableType(scope.row)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div align="center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- =================== 新增分类对话框 ======================== -->
    <el-dialog title="新增分类" :visible.sync="addDialogVisible">
      <el-form :model="addTypeForm" ref="addTypeForm" :rules="rules">
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="addTypeForm.typeName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="addType">确 定</el-button>
      </div>
    </el-dialog>

    <!-- =================== 修改分类对话框 ======================== -->
    <el-dialog title="修改分类" :visible.sync="updateDialogVisible">
      <el-form :model="updateTypeForm" ref="updateTypeForm" :rules="updateRules" :label-width="formLabelWidth">
        <el-form-item label="ID" prop="typeId">
          <el-input v-model="updateTypeForm.typeId" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="updateTypeForm.typeName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="isDelete" :label-width="formLabelWidth">
          <el-select v-model="updateTypeForm.isDelete" placeholder="请选择状态">
            <el-option label="正常" value="0"></el-option>
            <el-option label="已删除" value="1"></el-option>
            <el-option label="已禁用" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button @click="updateResetForm">重 置</el-button>
        <el-button type="primary" @click="toUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {Message} from "element-ui";

export default {
  name: "FlowerTypeView",
  data() {
    let checkFlowerTypeName = (rule, value, callback) => {
      let url = "/flowerType/checkFlowerTypeName/" + value;
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          callback();
        } else {
          this.getAllType();
          callback(new Error(res.data.message));
        }
      })
    };

    let checkFlowerTypeNameAndId = (rule, value, callback) => {
      let params1 = this.updateTypeForm.typeName
      let params2 = this.updateTypeForm.typeId
      let url = "/flowerType/checkFlowerTypeNameAndId/" + params1 + "/" + params2;
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          callback();
        } else {
          this.getAllType();
          callback(new Error(res.data.message));
        }
      })
    };


    return {
      formLabelWidth: '120px',
      isSearching: false,
      likeName: "",
      isDelete: "",


      typeList: [
        {isDelete: 0},
        {isDelete: 1},
        {isDelete: 2},
      ],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      name: "",
      addDialogVisible: false,

      addTypeForm: {
        typeName: ""
      },

      updateDialogVisible: false,
      updateTypeForm: {
        typeName: "",
        isDelete: "",
      },

      rules: {
        typeName: [
          {required: true, message: '请输入分类名称', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在2到10之间', trigger: 'blur'},
          {validator: checkFlowerTypeName, trigger: 'blur'}
        ]
      },
      updateRules: {
        typeName: [
          {required: true, message: '请输入分类名称', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在2到10之间', trigger: 'blur'},
          {validator: checkFlowerTypeNameAndId, trigger: 'blur'}
        ]
      },
    }
  },
  created() {
    this.getAllType();
  },
  methods: {
    // 通用分页函数
    getTypeList(url, params) {
      this.$axios.get(url, {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          ...params
        }
      }).then((res) => {
        if (res.data.code === 200) {
          this.typeList = res.data.data.list;
          this.total = res.data.data.total;
          this.pageNum = res.data.data.pageNum;
          this.pageSize = res.data.data.pageSize;
        }
      })
    },
    getAllType() {
      let url = "/flowerType/findFlowerTypeByPage";
      this.getTypeList(url, {});
    },

    searchType() {
      let url = "/flowerType/findFlowerTypeByConditions"
      this.getTypeList(url, {typeName: this.likeName, isDelete: this.isDelete});
      this.isSearching = true;
    },

    resetInput() {
      this.likeName = '';
      this.isDelete = '';
    },

    handleSizeChange(val) {
      this.pageSize = val;
      if (this.isSearching) {
        this.searchType();
      } else {
        this.getAllType();
      }
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      if (this.isSearching) {
        this.searchType();
      } else {
        this.getAllType();
      }
    },
    statusFormatter(row, column, cellValue) {
      if (cellValue === 0) {
        return '正常';
      } else if (cellValue === 1) {
        return '已删除';
      } else {
        return '已禁用';
      }
    },
    addType() {
      this.$refs['addTypeForm'].validate((valid) => {
        if (valid) {
          let url = "/flowerType/addFlowerType";
          let params = new URLSearchParams
          params.append("typeName", this.addTypeForm.typeName);
          this.$axios.post(url, params).then((res) => {
            if (res.data.code === 200) {
              Message({
                type: 'success',
                message: res.data.message,
                duration: 1000
              })
            } else {
              Message({
                type: 'error',
                message: res.data.message,
                duration: 1000
              })
            }
            this.addDialogVisible = false;
            this.getAllType();
          })
        }
      });
    },

    showEditDialog(row) {
      this.updateDialogVisible = true;
      this.updateTypeForm.typeId = row.typeId;
      this.updateTypeForm.typeName = row.typeName;
      // this.updateTypeForm.isDelete = row.isDelete === 0 ? '0' : '1';
      this.updateTypeForm.isDelete = row.isDelete === 0 ? '正常' : (row.isDelete === 1 ? '已删除' : '已禁用');

    },

    toUpdate() {
      this.$refs['updateTypeForm'].validate((valid) => {
        if (valid) {
          let url = "/flowerType/updateFlowerType";
          let params = new URLSearchParams
          params.append("typeId", this.updateTypeForm.typeId);
          params.append("typeName", this.updateTypeForm.typeName);
          params.append("isDelete", this.updateTypeForm.isDelete);
          this.$axios.put(url, params).then((res) => {
            if (res.data.code === 200) {
              Message({
                type: 'success',
                message: res.data.message,
                duration: 1000
              })
            } else {
              Message({
                type: 'error',
                message: res.data.message,
                duration: 1000
              })
            }
            this.updateDialogVisible = false;
            this.searchType();
          })
        }
      })
    },

    resetForm() {
      this.$refs['addTypeForm'].resetFields();
    },

    updateResetForm() {
      this.$refs['updateTypeForm'].resetFields();
    },

    removeType(row) {
      let url = "/flowerType/deleteFlowerType"
      let params = new URLSearchParams
      params.append("typeId", row.typeId);
      this.$axios.put(url, params).then((res) => {
        if (res.data.code === 200) {
          Message({
            type: 'success',
            message: res.data.message,
            duration: 1000
          })
        } else {
          Message({
            type: 'error',
            message: res.data.message,
            duration: 1000
          })
        }
        this.searchType();
      })
    },

    disableType(row) {
      let url = "/flowerType/disableFlowerType"
      let params = new URLSearchParams
      params.append("typeId", row.typeId);
      this.$axios.put(url, params).then((res) => {
        if (res.data.code === 200) {
          Message({
            type: 'success',
            message: res.data.message,
            duration: 1000
          })
        } else {
          Message({
            type: 'error',
            message: res.data.message,
            duration: 1000
          })
        }
        this.searchType();
      })
    },
  },
}

</script>